package com.sptpc.demo1.controller;

import com.sptpc.demo1.controller.requests.AddDrinkRequest;
import com.sptpc.demo1.controller.requests.ModifyDrinkRequest;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.service.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    public IDrinkService drinkService;
    //get /drink

    //@RequestMapping(value =  "/" , method = RequestMethod.GET)
    @GetMapping("/")
    public List<Drink> gatAll(Integer page, Integer limit) {
        PageRequest pageRequest = PageRequest.of(page - 1, limit);
        List<Drink> results = drinkService.getAllDrinks(pageRequest).getContent();
        return results;
    }

    /**
     * 查询指定的饮品
     * get /drink/1
     * get /drink/？id=1
     */
    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable Integer id) {
        log.info("要查询的饮品id:{}", id);
        //后期从数据库中查询
        Drink drink = Drink.builder().id(1)
                .name("茉莉绿茶")
                .price(Money.parse("USD 8.00"))
                .build();
        return drink;
    }

    /**
     * 新建
     * post /drink /{"name" :"奶茶", "price":"8.00"}
     * 传参思路
     * 1.直接使用实体类
     * 2.根据前参数编写TO类
     */
    @PostMapping("/")
    public Drink addNewDrink(@RequestBody @Valid AddDrinkRequest drink,
                             BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError allError : bindingResult.getAllErrors()) {
                log.error(allError.toString());
            }
            return null;
        } else {
            log.info("新增饮品{}", drink);
            Drink saveDrink = new Drink();
            BeanUtils.copyProperties(drink, saveDrink);

            drinkService.addNewDrink(saveDrink, drink.getCategoryId());
            //drinkRepository.save(drink);
            return saveDrink;
        }
    }

    /**
     * 修改
     * put /drink/{"name" :"新名字", "price":"9.00"}
     */
    @PutMapping("/")
    public Drink modfiyDrink(@RequestBody ModifyDrinkRequest request) {
        log.info("修改饮品{}", request);
        //1.    查看是否有无该饮品
        Drink drink = drinkService.getDrinkById(request.getId());
        //2.    要把要修改的内容 对应drink属性
        BeanUtils.copyProperties(request, drink);
        //3.    更新数据库
        drinkService.setDrink(drink, request.getCategoryId());
        return drink;
    }

    /**
     * 删除
     * delete /drink/1
     */
    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id) {
        log.info("要删除的饮品{}", id);
        drinkService.deleteDrinkById(id);
        return id + "删除成功";
    }

    /**
     * 文件上传
     */
    @PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String uploadFile(MultipartFile file) {
        String path = "D:/localdata";
        String filepath = path + file.getOriginalFilename();
        File savefile = new File(filepath);
        try {
            file.transferTo(savefile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }

    /**
     * 批量上传数据
     * MultipartFile方法 getInputstremm
     */
    @PostMapping(value = "/batch", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public List<Drink> batchAddNewDrinks(MultipartFile file) {
        List<Drink> results = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                //解析每一行 1,焦糖拿铁,15.00
                String[] arge = line.split(",");
                results.add(Drink.builder().id(Integer.parseInt(arge[0]))
                        .name(arge[1])
                        .price(Money.of(CurrencyUnit.of("CNY"), Double.parseDouble(arge[2])))
                        .build());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return results;
    }

}
